package com.zc.portal.infra.security.http;

import com.alibaba.fastjson.JSON;
import com.zc.commons.pojo.AuthenticatedUser;
import com.zc.portal.domain.dto.SysUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Base64;

@Deprecated
public class ReqHandleWrapper extends HttpServletRequestWrapper {

    private static final String X_TOKEN = "x-token";
    private static final String AUTHORIZATION = "Authorization";

    private SysUser sysUser;


    public ReqHandleWrapper(HttpServletRequest request) {
        super(request);
    }


    @Override
    public Principal getUserPrincipal() {
        return super.getUserPrincipal();
    }

    @Override
    public String getHeader(String name) {

        if (X_TOKEN.equals(name) || AUTHORIZATION.equals(name)) {
            try {
                return encryptToken();
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        return super.getHeader(name);
    }

    public void setSysUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    /**
     * 公用的认证用户信息简单加密
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    private String encryptToken() throws UnsupportedEncodingException {

        AuthenticatedUser user = new AuthenticatedUser();
        if (this.sysUser != null) {
            user.setUserCode(sysUser.getUserCode());
            user.setUserName(sysUser.getUserName());
            user.setUserId(sysUser.getUserId());
            user.setDeptId(sysUser.getDeptId());
            user.setPostCode(sysUser.getPostCode());
        }
        String userJsonStr = JSON.toJSONString(user);
        byte[] bytes = userJsonStr.getBytes("utf-8");
        String encode = Base64.getEncoder().encodeToString(bytes);
        return encode;
    }
}
